<template>
  <div>
    <Editor
        v-model="myValue"
        :init="init"
        :disabled="disabled"
        :placeholder="placeholder"
        :id="tinymceId"
    ></Editor>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, defineEmits, watch } from "vue";
import Editor from "@tinymce/tinymce-vue";
import tinymce from "tinymce/tinymce";
import "tinymce/themes/silver";
import "tinymce/themes/silver/theme";
import "tinymce/models/dom";
import "tinymce/icons/default";
import "tinymce/icons/default/icons";
// 引入编辑器插件
import "tinymce/plugins/code"; //编辑源码
import "tinymce/plugins/image"; //插入编辑图片
import "tinymce/plugins/media"; //插入视频
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/template"; //模板
import "tinymce/plugins/table"; //表格
import "tinymce/plugins/pagebreak"; //分页
import "tinymce/plugins/lists"; //列
import "tinymce/plugins/advlist"; //列
import "tinymce/plugins/quickbars"; //快速工具条
import "tinymce/plugins/wordcount"; // 字数统计插件
// import "tinymce/langs/zh-Hans.js"; //下载后的语言包
import "tinymce/skins/content/default/content.css";
const emits = defineEmits(["update:value"]);

import {uploadFile, uploadFilePath} from "@/apis/http/system/FileHttp";

const uploadFileUrl = uploadFilePath()

const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  height: {
    type: Number,
    default: 500,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  plugins: {
    type: [String, Array],
    default:
        "code image media link preview table quickbars template pagebreak lists advlist",
  },
  toolbar: {
    type: [String, Array],
    default:
        "undo redo codesample bold italic underline strikethrough link alignleft aligncenter alignright alignjustify \
        bullist numlist outdent indent removeformat forecolor backcolor |formatselect fontselect fontsizeselect | \
        blocks fontfamily fontsize pagebreak lists image media table template preview | code selectall",
  },
  templates: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Object,
    default: () => {},
  },
});
//用于接收外部传递进来的富文本
const myValue = ref(props.value);
const tinymceId = ref(
    "vue-tinymce-" + +new Date() + ((Math.random() * 1000).toFixed(0) + "")
);
const init = reactive({
  selector: "#" + tinymceId.value, //富文本编辑器的id,
  language_url: "tinymce/langs/zh-Hans.js", // 语言包的路径，具体路径看自己的项目，文档后面附上中文js文件
  language: "zh-Hans", //语言
  skin_url: "tinymce/skins/ui/oxide", // skin路径，具体路径看自己的项目
  content_css: "tinymce/skins/content/default/content.css",
  menubar: true, //顶部菜单栏显示
  statusbar: true, // 底部的状态栏
  plugins: props.plugins,
  toolbar: props.toolbar,
  toolbar_mode: "sliding",
  font_formats:
      "Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;", //字体
  paste_convert_word_fake_lists: false, // 插入word文档需要该属性
  font_size_formats: "12px 14px 16px 18px 22px 24px 36px 72px", //文字大小
  height: props.height, //编辑器高度
  placeholder: props.placeholder,
  branding: false, //是否禁用“Powered by TinyMCE”
  image_dimensions: false, //去除宽高属性
  paste_webkit_styles: "all",
  paste_merge_formats: true,
  nonbreaking_force_tab: false,
  paste_auto_cleanup_on_paste: false,
  file_picker_types: "file",
  resize: true,
  elementpath: true,
  content_style: "",
  templates: props.templates,
  quickbars_selection_toolbar:
      "forecolor backcolor bold italic underline strikethrough link",
  quickbars_image_toolbar: "alignleft aligncenter alignright",
  quickbars_insert_toolbar: false,
  image_caption: true,
  image_advtab: true,
  convert_urls: false,
  images_upload_handler: function (blobInfo, progress) {
    return new Promise((resolve, reject) => {
      console.log("图片上传处理：", blobInfo.blob());
      const formData = new FormData();
      formData.append("file", blobInfo.blob());
      debugger
      uploadFile(formData).then(res => {
        console.log('上传文件')
        console.log(res)
        // success(res.data.url)
        resolve(res.data.url)
        // success('https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0')
      }).catch(error => {
        reject(error);
      });
    });
  },
  // 文件上传
  file_picker_callback: (callback, value, meta) => {
    // Provide file and text for the link dialog
    if (meta.filetype == "file") {
      callback("mypage.html", { text: "My text" });
    }
    // Provide image and alt text for the image dialog
    if (meta.filetype == "image") {
      callback("myimage.jpg", { alt: "My alt text" });
    }
    // Provide alternative source and posted for the media dialog
    if (meta.filetype == "media") {
      callback("movie.mp4", { source2: "alt.ogg", poster: "image.jpg" });
    }
  },
  setup: function (editor) {
    editor.on("init", function () {
      this.getBody().style.fontSize = "14px";
    });
    editor.on("OpenWindow", function (e) {
      //FIX 编辑器在el-drawer中，编辑器的弹框无法获得焦点
      var D = document.querySelector(".el-drawer.open");
      var E = e.target.editorContainer;
      if (D && D.contains(E)) {
        var nowDA = document.activeElement;
        setTimeout(() => {
          document.activeElement.blur();
          nowDA.focus();
        }, 0);
      }
    });
  },
  ...props.options,
});
//监听外部传递进来的的数据变化
watch(
    () => props.value,
    () => {
      myValue.value = props.value;
      emits("update:value", myValue.value);
    }
);
//监听富文本中的数据变化
watch(
    () => myValue.value,
    () => {
      emits("update:value", myValue.value);
    }
);
//在onMounted中初始化编辑器
onMounted(() => {
  tinymce.init({});
});
</script>
<style>
</style>
